# -*- coding: UTF-8 -*-

import logging

from pylons import request, response, session, tmpl_context as c
from pylons.controllers.util import abort, redirect_to, redirect
from pylons import app_globals

from kooka.lib.base import BaseController, render
from kooka.lib.helpers import *

import kooka.model.meta as meta
from kooka.model import NewsCategory, ExportConfig, ProductCategory
from sqlalchemy import or_, and_

import os
import codecs
log = logging.getLogger(__name__)

class AdminfrontController(BaseController):

    def list(self):
        c.rootpath = os.path.join(app_globals.apprunpath,'templates/front/')
        c.basefiles = os.listdir(os.path.join(c.rootpath,'base'))
        c.basefiles.sort()
        c.derivedfiles = os.listdir(os.path.join(c.rootpath,'derived'))
        c.derivedfiles.sort()
        return render('/admin/derived/front/list.html')

    def beginedit(self):
        #get file content
        c.folder = request.params['folder']
        c.file = request.params['file']
        f = open(os.path.join(app_globals.apprunpath,'templates/front/',c.folder,c.file),'r')
        c.filecontent = f.read()
        f.close()

        #get all news category
        newscategory_q = meta.Session.query(NewsCategory)
        c.news_categories = newscategory_q.filter(or_(NewsCategory.fk_FatherCategory==None,NewsCategory.fk_FatherCategory==-1)).order_by("sort").all()

        #get all users role
        users = request.environ['authkit.users']
        c.member_roles = users.list_roles()
        
        #get all product category
        productcategory_q = meta.Session.query(ProductCategory)
        c.product_categories = productcategory_q.filter(or_(ProductCategory.fk_productcategory==None,ProductCategory.fk_productcategory==-1)).order_by("sort").all()

        #get all export method info
        exportconfig_q = meta.Session.query(ExportConfig)
        c.methods = exportconfig_q.filter(and_(ExportConfig.page==os.path.splitext(c.file)[0],ExportConfig.module!='auth')).all()

        #get auth method info
        c.authmethods = exportconfig_q.filter(and_(ExportConfig.page==os.path.splitext(c.file)[0],ExportConfig.module=='auth')).all()

        return render('/admin/derived/front/edit.html')

    def endedit(self):
        #update the file content
        folder = request.params['folder']
        file = request.params['file']
        page = os.path.splitext(file)[0]
        f = codecs.open(os.path.join(app_globals.apprunpath,'templates/front/',folder,file),'w','utf-8')
        f.write(request.params['filecontent'])
        f.close()

        #update the export method info
        #the auth config
        #case new record
        if request.params['auth_id']=="-1":
            exportconfig = ExportConfig()
            exportconfig.page = page
            exportconfig.module = 'auth' 
            exportconfig.category= request.params.get('hasauthcheck','')
            exportconfig.method = request.params["auth_roles"]
            exportconfig.params1 = request.params["auth_params1"]
            meta.Session.add(exportconfig)
        else:
            exportconfig_q = meta.Session.query(ExportConfig)
            exportconfig = exportconfig_q.get(int(request.params['auth_id']))
            exportconfig.module = 'auth' 
            exportconfig.category= request.params.get('hasauthcheck','')
            exportconfig.method = request.params["auth_roles"]
            exportconfig.params1 = request.params["auth_params1"]

        #the 10 export method
        for i in range(1,11):
            #case new record
            if request.params['id'+ str(i)]=="-1":
                exportconfig = ExportConfig()
                exportconfig.page = page
                exportconfig.module = request.params["module"+str(i)]
                exportconfig.category= request.params["category"+str(i)]
                exportconfig.method = request.params["method"+str(i)]
                exportconfig.params1 = request.params["params1"+str(i)]
                exportconfig.params2 = request.params["params2"+str(i)]
                exportconfig.params3 = request.params["params3"+str(i)]
                exportconfig.params4 = request.params["params4"+str(i)]
                exportconfig.result = request.params["result"+str(i)]
                meta.Session.add(exportconfig)
            #case existed record
            elif request.params['id' + str(i)]!="-1":
                exportconfig_q = meta.Session.query(ExportConfig)
                exportconfig = exportconfig_q.get(int(request.params['id' + str(i)]))
                if request.params.get('deletemethod'+str(i),'0') == '1':
                    meta.Session.delete(exportconfig)
                else:
                    exportconfig.module = request.params["module"+str(i)]
                    exportconfig.category= request.params["category"+str(i)]
                    exportconfig.method = request.params["method"+str(i)]
                    exportconfig.params1 = request.params["params1"+str(i)]
                    exportconfig.params2 = request.params["params2"+str(i)]
                    exportconfig.params3 = request.params["params3"+str(i)]
                    exportconfig.params4 = request.params["params4"+str(i)]
                    exportconfig.result = request.params["result"+str(i)]
        meta.Session.commit()

        session['flash'] = '编辑成功'
        session.save()

        redirect(url_for(action='list'))


    def beginadd(self):
        return render('/admin/derived/front/add.html')

    def endadd(self):
        rootpath = os.path.join(app_globals.apprunpath,'templates/front/')
        folder = request.params['folder']
        if request.params.get('filename','') != '':
            f = open(os.path.join(rootpath, folder, request.params['filename']), 'w')
            f.close()

        session['flash'] = '新增成功'
        session.save()

        redirect(url_for(action='list'))

    def delete(self):
        rootpath = os.path.join(app_globals.apprunpath,'templates/front/')
        folder = request.params['folder']
        if request.params.get('file','') != '':
            os.remove(os.path.join(rootpath, folder, request.params['file']))

        session['flash'] = '删除成功'
        session.save()

        redirect(url_for(action='list'))








